package com.ncloud.resman.busi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.common.utils.DateUtils;
import com.ncloud.common.utils.excel.ExcelUtil;
import com.ncloud.resman.constant.ResConstant;
import com.ncloud.resman.entity.*;
import com.ncloud.resman.mapper.DictMapper;
import com.ncloud.resman.service.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;


/**
 * Created by shiqiang on 2017/8/15.
 */
@Service
public class DeviceServerBusi {
    @Autowired
    private DeviceServerService deviceServerService;
    @Autowired
    private DeviceSwitchService deviceSwitchService;
    @Autowired
    private DeviceLocationService deviceLocationService;
    @Autowired
    private DeviceBaseService deviceBaseService;
    @Autowired
    private DeviceUnitService deviceUnitService;
    @Autowired
    private DeviceIpService deviceIpService;
    @Autowired
    private DeviceSwitchSubService deviceSwitchSubService;
    @Autowired
	private DictMapper dictMapper;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CabinetService cabinetServer;
    @Autowired
    private ModelService modelService;
    /*新增服务器*/
    @Transactional
    public void addDeviceSever(JSONObject json){
        if(json == null ){
            throw new UserException(ResultEnum.PARAM_ERROR);
        }
        Long userId = null;

        if(json.containsKey("userID")){
            userId = json.getLong("userID");
        }else{
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"userID 信息不存在");
        }
        //设备类型处理
       /* if(json.containsKey("deviceType")){

        }else {
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"请传入要处理的服务器类型deviceType{服务器：1,交换机：2，防火墙：3}");
        }*/

        //String deviceType = json.getString("deviceType");
        /*device_base*/
        DeviceBase deviceBase = null;

        if(json.containsKey("device_base")){
           JSONObject base = json.getJSONObject("device_base");
            deviceBase = JSON.parseObject(base.toJSONString(),DeviceBase.class);
            deviceBase.setCreateUser(userId);
            if(StringUtils.isEmpty(deviceBase.getState())){
                deviceBase.setState(ResConstant.DEVICE_STATE_FREE);
            }
            deviceBaseService.insertDeviceBase(deviceBase);
            System.out.println("device_id="+deviceBase.getDeviceId());

            /*处理设备位置*/
            DeviceLocation deviceLocation = new DeviceLocation();
            deviceLocation.setDeviceId(deviceBase.getDeviceId());
            deviceLocation.setCreateUser(userId);
            deviceLocation.setSnNum(deviceBase.getSnNum());
            deviceLocation.setState(ResConstant.DEVICE_LOCATION_UNONLINE);
            deviceLocationService.insertLocation(deviceLocation);
            if(ResConstant.EQPT_TYPE_SERVER.equals(deviceBase.getEqptType())){
                /*device_sever*/
                if(json.containsKey("device_server")){
                    JSONObject server = json.getJSONObject("device_server");
                    DeviceServer deviceServer = JSON.parseObject(server.toJSONString(),DeviceServer.class);
                    deviceServer.setDeviceId(deviceBase.getDeviceId());
                    deviceServer.setCreateUser(userId);
                    deviceServerService.insertDeviceServer(deviceServer);
                }else{
                    DeviceServer deviceServer = new DeviceServer();
                    deviceServer.setDeviceId(deviceBase.getDeviceId());
                    deviceServer.setCreateUser(userId);
                    deviceServerService.insertDeviceServer(deviceServer);
                }
                /*device_unit 数组*/
                final Long  deviceId = deviceBase.getDeviceId();
                //插入
                insertArrayInfo(json,deviceId);
            }else if(ResConstant.EQPT_TYPE_SWITCH.equals(deviceBase.getEqptType())){
                if(json.containsKey("device_switch")){
                    JSONObject server = json.getJSONObject("device_switch");
                    DeviceSwitch deviceSwitch = JSON.parseObject(server.toJSONString(),DeviceSwitch.class);
                    deviceSwitch.setDeviceId(deviceBase.getDeviceId());
                    deviceSwitch.setCreateUser(userId);
                    deviceSwitchService.insertDeviceSwitch(deviceSwitch);
                    insertArrayInfoSwitch(deviceSwitch);
                }else{
                    throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"device_sever 节点信息不存在！");
                }
            }
        }else{
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"device_base 节点信息不存在！");
        }
    }
    
    
    /*更新服务器*/
    @Transactional
    public void modifyDeviceSever(JSONObject json){
        if(json == null ){
            throw new UserException(ResultEnum.PARAM_ERROR);
        }
        Long userId = null;
        DeviceBase deviceBase = null;

        if(json.containsKey("userID")){
            userId = json.getLong("userID");
        }else{
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"userID 信息不存在");
        }
        /*device_base*/
        if(json.containsKey("device_base")){
            JSONObject base = json.getJSONObject("device_base");
            deviceBase = JSON.parseObject(base.toJSONString(),DeviceBase.class);
            deviceBase.setUpdateUser(userId);
            deviceBaseService.updateDeviceBase(deviceBase);

            //处理位置信息,如果sn号发生变化，更新位置编码信息
            DeviceLocation deviceLocationOld = deviceLocationService.getLocationByDeviceId(deviceBase.getDeviceId());
            if(!deviceLocationOld.getSnNum().equals(deviceBase.getSnNum())){
                deviceLocationService.updateLocationSnNumByDeviceId(deviceBase.getSnNum(),deviceBase.getDeviceId());
            }

            if(ResConstant.EQPT_TYPE_SERVER.equals(deviceBase.getEqptType())){
                /*device_sever*/
                if(json.containsKey("device_server")){
                    JSONObject server = json.getJSONObject("device_server");
                    DeviceServer deviceServer = JSON.parseObject(server.toJSONString(),DeviceServer.class);
                    deviceServer.setUpdateUser(userId);
                    deviceServerService.updateDeviceServer(deviceServer);

                    /*device_unit 数组*/
                    final Long  deviceId = deviceBase.getDeviceId();
                    //删除所有组件
                    deviceUnitService.deleteDeviceUnit(deviceId);
                    insertArrayInfo(json,deviceId);
                }else{
                    throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"device_sever 节点信息不存在！");
                }
            }else if(ResConstant.EQPT_TYPE_SWITCH.equals(deviceBase.getEqptType())){

                /*交换机*/
                if(json.containsKey("device_switch")){
                    JSONObject server = json.getJSONObject("device_switch");
                    DeviceSwitch deviceSwitch = JSON.parseObject(server.toJSONString(),DeviceSwitch.class);
                    deviceSwitch.setUpdateUser(userId);
                    deviceSwitchService.updateSwitchBase(deviceSwitch);

                }else{
                    throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"device_sever 节点信息不存在！");
                }
            }
        }
    }

    private void insertArrayInfo(JSONObject json,Long deviceId){
        //插入
        if(json.containsKey("device_unit")){
            JSONArray unitList = json.getJSONArray("device_unit");
            unitList.stream().forEach(o -> {
                DeviceUnit deviceUnit = JSON.parseObject(JSON.toJSONString(o),DeviceUnit.class);
                deviceUnit.setDeviceId(deviceId);
                deviceUnit.setUseTag("1");
                //插入
                deviceUnitService.insertDeviceUnit(deviceUnit);
            });
        }else{
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"device_unit 节点信息不存在！");
        }
    }


    private void insertArrayInfoSwitch(DeviceSwitch deviceSwitch){
        //插入
        if(deviceSwitch.getInterfaceNum()!=null){
            for(int i=0;i<deviceSwitch.getInterfaceNum();i++){
                DeviceSub deviceSub = new DeviceSub();
                deviceSub.setDeviceId(deviceSwitch.getDeviceId());
                deviceSub.setSubType(ResConstant.SUB_TYPE);
                deviceSub.setState(ResConstant.SUB_STATE_OTHER);
                deviceSub.setCreateUser(deviceSwitch.getCreateUser());
                deviceSub.setSubNo(i+1);
                //插入
                deviceSwitchSubService.insertDeviceSubSwitch(deviceSub);
            }
        }
        if(deviceSwitch.getG40Num()!=null){
            for(int i=0;i<deviceSwitch.getG40Num();i++){
                DeviceSub deviceSub = new DeviceSub();
                deviceSub.setDeviceId(deviceSwitch.getDeviceId());
                deviceSub.setSubType(ResConstant.SUB_TYPE_40G);
                deviceSub.setState(ResConstant.SUB_STATE_OTHER);
                deviceSub.setCreateUser(deviceSwitch.getCreateUser());
                deviceSub.setSubNo(deviceSwitch.getInterfaceNum()+1);
                //插入
                deviceSwitchSubService.insertDeviceSubSwitch(deviceSub);
            }
        }
        //
        DeviceSub deviceSub = new DeviceSub();
        deviceSub.setDeviceId(deviceSwitch.getDeviceId());
        deviceSub.setSubType(ResConstant.SUB_TYPE_MANAGER);
        deviceSub.setState(ResConstant.SUB_STATE_OTHER);
        deviceSub.setCreateUser(deviceSwitch.getCreateUser());
        deviceSub.setSubNo(deviceSwitch.getInterfaceNum()+deviceSwitch.getG40Num()+1);
        //插入
        deviceSwitchSubService.insertDeviceSubSwitch(deviceSub);
    }

    /*查询服务器信息*/
    public JSONObject getDeviceServerInfo(Long deviceId){
        JSONObject result = new JSONObject();
        DeviceBase deviceBase = deviceBaseService.getDeviceBaseByDeviceId(deviceId);
        DeviceServer deviceServer = deviceServerService.getDeviceServerByDeviceId(deviceId);
        //List<JSONObject> ipList = deviceIpService.getDeviceIpById(deviceId);
        List<JSONObject> unitList = deviceUnitService.getDeviceUnitById(deviceId);
        result.put("device_base",deviceBase);
        result.put("device_server",deviceServer);
        //result.put("device_ip",ipList);
        result.put("device_unit",unitList);
        return result;
    }

    /*查询交换机信息*/
    public JSONObject getDeviceSwitchInfo(Long deviceId){
        JSONObject result = new JSONObject();
        DeviceBase deviceBase = deviceBaseService.getDeviceBaseByDeviceId(deviceId);
        DeviceSwitch deviceSwitch = deviceSwitchService.getDeviceSwitchByDeviceId(deviceId);
        result.put("device_base",deviceBase);
        result.put("device_switch",deviceSwitch);
        return result;
    }

    /*查询防火墙信息*/
    public JSONObject getDeviceFirewallInfo(Long deviceId){
        JSONObject result = new JSONObject();
        DeviceBase deviceBase = deviceBaseService.getDeviceBaseByDeviceId(deviceId);
        result.put("device_base",deviceBase);
        return result;
    }

    /*修改设备接口状态*/
    public void updateSwitchSubPurpose(DeviceSub deviceSub){
        deviceSwitchSubService.updateSwitchSubPurpose(deviceSub);
    }
}
